<template>
  <div class="route-container">
    <div class="page-header">
      <div class="header-title">
        <h2>路线地图</h2>
        <span class="subtitle">管理常用运输路线和地图信息</span>
      </div>
      <div class="header-actions">
        <el-button type="primary" @click="openAddRouteDialog">
          <el-icon><Plus /></el-icon>添加路线
        </el-button>
        <el-button @click="refreshRoutes">
          <el-icon><Refresh /></el-icon>刷新
        </el-button>
      </div>
    </div>

    <!-- 搜索过滤区域 -->
    <el-card class="filter-container">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="路线名称">
          <el-input v-model="filterForm.name" placeholder="请输入路线名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="起点城市">
          <el-select v-model="filterForm.startCity" placeholder="选择起点城市" clearable>
            <el-option v-for="city in cities" :key="city.value" :label="city.label" :value="city.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="终点城市">
          <el-select v-model="filterForm.endCity" placeholder="选择终点城市" clearable>
            <el-option v-for="city in cities" :key="city.value" :label="city.label" :value="city.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="路线类型">
          <el-select v-model="filterForm.type" placeholder="选择路线类型" clearable>
            <el-option label="高速公路" value="highway"></el-option>
            <el-option label="国道" value="national"></el-option>
            <el-option label="省道" value="provincial"></el-option>
            <el-option label="城市道路" value="urban"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchRoutes">查询</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 路线列表和地图区域 -->
    <el-row :gutter="20" class="content-row">
      <!-- 左侧：路线列表 -->
      <el-col :span="8">
        <el-card class="route-list-card">
          <template #header>
            <div class="card-header">
              <span>路线列表</span>
              <el-switch
                v-model="showActiveOnly"
                active-text="仅显示启用"
                inactive-text="显示全部"
                @change="filterRoutes"
              ></el-switch>
            </div>
          </template>
          
          <el-table
            :data="filteredRoutes"
            style="width: 100%"
            @row-click="selectRoute"
            :row-class-name="getRowClassName"
            v-loading="loading"
          >
            <el-table-column prop="name" label="路线名称" min-width="120"></el-table-column>
            <el-table-column prop="startCity" label="起点" width="100"></el-table-column>
            <el-table-column prop="endCity" label="终点" width="100"></el-table-column>
            <el-table-column prop="distance" label="距离(km)" width="100"></el-table-column>
            <el-table-column prop="status" label="状态" width="80">
              <template #default="scope">
                <el-tag :type="scope.row.status === 'active' ? 'success' : 'info'">
                  {{ scope.row.status === 'active' ? '启用' : '禁用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150" fixed="right">
              <template #default="scope">
                <el-button 
                  size="small" 
                  type="primary" 
                  @click.stop="editRoute(scope.row)"
                >
                  编辑
                </el-button>
                <el-button 
                  size="small" 
                  type="danger" 
                  @click.stop="deleteRoute(scope.row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="totalRoutes"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            ></el-pagination>
          </div>
        </el-card>
      </el-col>
      
      <!-- 右侧：地图 -->
      <el-col :span="16">
        <el-card class="map-card">
          <template #header>
            <div class="card-header">
              <span>路线地图</span>
              <div class="map-controls">
                <el-button-group>
                  <el-button size="small" @click="zoomIn">
                    <el-icon><ZoomIn /></el-icon>
                  </el-button>
                  <el-button size="small" @click="zoomOut">
                    <el-icon><ZoomOut /></el-icon>
                  </el-button>
                  <el-button size="small" @click="resetMap">
                    <el-icon><RefreshRight /></el-icon>
                  </el-button>
                </el-button-group>
              </div>
            </div>
          </template>
          
          <div class="map-container">
            <!-- 高德地图组件 -->
            <div id="map-container" ref="mapContainer" class="amap-container"></div>
            <div v-if="!selectedRoute && !mapLoaded" class="map-loading">
              <el-icon class="loading-icon"><Loading /></el-icon>
              <p>地图加载中...</p>
            </div>
          </div>
          
          <!-- 路线详情 -->
          <div v-if="selectedRoute" class="route-details">
            <h3>路线详情</h3>
            <el-descriptions :column="2" border>
              <el-descriptions-item label="路线名称">{{ selectedRoute.name }}</el-descriptions-item>
              <el-descriptions-item label="路线类型">{{ getRouteTypeName(selectedRoute.type) }}</el-descriptions-item>
              <el-descriptions-item label="起点">{{ selectedRoute.startCity }}</el-descriptions-item>
              <el-descriptions-item label="终点">{{ selectedRoute.endCity }}</el-descriptions-item>
              <el-descriptions-item label="距离">{{ selectedRoute.distance }} km</el-descriptions-item>
              <el-descriptions-item label="预计时间">{{ selectedRoute.estimatedTime }}</el-descriptions-item>
              <el-descriptions-item label="途经点" :span="2">
                {{ selectedRoute.viaPoints.join(' → ') }}
              </el-descriptions-item>
              <el-descriptions-item label="备注" :span="2">
                {{ selectedRoute.remarks || '无' }}
              </el-descriptions-item>
            </el-descriptions>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 添加/编辑路线对话框 -->
    <el-dialog
      v-model="routeDialogVisible"
      :title="isEditMode ? '编辑路线' : '添加路线'"
      width="650px"
    >
      <el-form
        ref="routeFormRef"
        :model="routeForm"
        :rules="routeRules"
        label-width="100px"
      >
        <el-form-item label="路线名称" prop="name">
          <el-input v-model="routeForm.name" placeholder="请输入路线名称"></el-input>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="起点城市" prop="startCity">
              <el-select v-model="routeForm.startCity" placeholder="选择起点城市" style="width: 100%">
                <el-option v-for="city in cities" :key="city.value" :label="city.label" :value="city.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="终点城市" prop="endCity">
              <el-select v-model="routeForm.endCity" placeholder="选择终点城市" style="width: 100%">
                <el-option v-for="city in cities" :key="city.value" :label="city.label" :value="city.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="路线类型" prop="type">
              <el-select v-model="routeForm.type" placeholder="选择路线类型" style="width: 100%">
                <el-option label="高速公路" value="highway"></el-option>
                <el-option label="国道" value="national"></el-option>
                <el-option label="省道" value="provincial"></el-option>
                <el-option label="城市道路" value="urban"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="routeForm.status">
                <el-radio label="active">启用</el-radio>
                <el-radio label="inactive">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="距离(km)" prop="distance">
              <el-input-number v-model="routeForm.distance" :min="0" :precision="1" style="width: 100%"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预计时间" prop="estimatedTime">
              <el-input v-model="routeForm.estimatedTime" placeholder="如: 2小时30分钟"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="途经点" prop="viaPoints">
          <el-select
            v-model="routeForm.viaPoints"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="请输入途经点，回车确认"
            style="width: 100%"
          >
            <el-option
              v-for="item in viaPointOptions"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input
            v-model="routeForm.remarks"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="routeDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveRoute">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Plus, 
  Refresh, 
  ZoomIn, 
  ZoomOut, 
  RefreshRight, 
  Location 
} from '@element-plus/icons-vue'
// 移除 AMapLoader 导入
// import AMapLoader from '@amap/amap-jsapi-loader'

// 加载状态
const loading = ref(false)

// 路线列表
const routes = ref([
  {
    id: 1,
    name: '京沪高速',
    startCity: '北京',
    endCity: '上海',
    type: 'highway',
    distance: 1200,
    estimatedTime: '12小时',
    viaPoints: ['天津', '济南', '徐州', '南京'],
    status: 'active',
    remarks: '全程高速，路况良好'
  },
  {
    id: 2,
    name: '京广高速',
    startCity: '北京',
    endCity: '广州',
    type: 'highway',
    distance: 2200,
    estimatedTime: '22小时',
    viaPoints: ['石家庄', '郑州', '武汉', '长沙'],
    status: 'active',
    remarks: '全程高速，部分路段可能有施工'
  },
  {
    id: 3,
    name: '沪蓉高速',
    startCity: '上海',
    endCity: '成都',
    type: 'highway',
    distance: 1800,
    estimatedTime: '18小时',
    viaPoints: ['南京', '合肥', '武汉', '重庆'],
    status: 'active',
    remarks: '全程高速，山区路段较多'
  },
  {
    id: 4,
    name: '京津城际',
    startCity: '北京',
    endCity: '天津',
    type: 'urban',
    distance: 120,
    estimatedTime: '1小时30分钟',
    viaPoints: ['廊坊'],
    status: 'active',
    remarks: '城际快速路，交通便利'
  },
  {
    id: 5,
    name: '沪杭高速',
    startCity: '上海',
    endCity: '杭州',
    type: 'highway',
    distance: 180,
    estimatedTime: '2小时',
    viaPoints: ['嘉兴'],
    status: 'active',
    remarks: '全程高速，路况良好'
  },
  {
    id: 6,
    name: '京哈国道',
    startCity: '北京',
    endCity: '哈尔滨',
    type: 'national',
    distance: 1200,
    estimatedTime: '15小时',
    viaPoints: ['承德', '沈阳', '长春'],
    status: 'inactive',
    remarks: '国道，部分路段为高速'
  },
  {
    id: 7,
    name: '广深高速',
    startCity: '广州',
    endCity: '深圳',
    type: 'highway',
    distance: 140,
    estimatedTime: '1小时30分钟',
    viaPoints: ['东莞'],
    status: 'active',
    remarks: '全程高速，交通便利'
  }
])

// 城市列表
const cities = [
  { value: '北京', label: '北京' },
  { value: '上海', label: '上海' },
  { value: '广州', label: '广州' },
  { value: '深圳', label: '深圳' },
  { value: '天津', label: '天津' },
  { value: '重庆', label: '重庆' },
  { value: '成都', label: '成都' },
  { value: '杭州', label: '杭州' },
  { value: '武汉', label: '武汉' },
  { value: '西安', label: '西安' },
  { value: '南京', label: '南京' },
  { value: '长沙', label: '长沙' },
  { value: '济南', label: '济南' },
  { value: '哈尔滨', label: '哈尔滨' },
  { value: '沈阳', label: '沈阳' }
]

// 途经点选项
const viaPointOptions = [
  '天津', '廊坊', '石家庄', '济南', '徐州', '南京', 
  '合肥', '杭州', '苏州', '郑州', '武汉', '长沙', 
  '重庆', '东莞', '嘉兴', '沈阳', '长春'
]

// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const totalRoutes = ref(routes.value.length)

// 筛选表单
const filterForm = ref({
  name: '',
  startCity: '',
  endCity: '',
  type: ''
})

// 只显示启用的路线
const showActiveOnly = ref(false)

// 选中的路线
const selectedRoute = ref(null)

// 路线对话框
const routeDialogVisible = ref(false)
const isEditMode = ref(false)
const routeFormRef = ref(null)

// 路线表单
const routeForm = ref({
  id: null,
  name: '',
  startCity: '',
  endCity: '',
  type: 'highway',
  distance: 0,
  estimatedTime: '',
  viaPoints: [],
  status: 'active',
  remarks: ''
})

// 表单验证规则
const routeRules = {
  name: [
    { required: true, message: '请输入路线名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  startCity: [
    { required: true, message: '请选择起点城市', trigger: 'change' }
  ],
  endCity: [
    { required: true, message: '请选择终点城市', trigger: 'change' }
  ],
  type: [
    { required: true, message: '请选择路线类型', trigger: 'change' }
  ],
  distance: [
    { required: true, message: '请输入距离', trigger: 'blur' }
  ],
  estimatedTime: [
    { required: true, message: '请输入预计时间', trigger: 'blur' }
  ]
}

// 筛选后的路线
const filteredRoutes = computed(() => {
  let result = routes.value

  // 关键词筛选
  if (filterForm.value.name) {
    result = result.filter(route => 
      route.name.toLowerCase().includes(filterForm.value.name.toLowerCase())
    )
  }

  // 起点城市筛选
  if (filterForm.value.startCity) {
    result = result.filter(route => 
      route.startCity === filterForm.value.startCity
    )
  }

  // 终点城市筛选
  if (filterForm.value.endCity) {
    result = result.filter(route => 
      route.endCity === filterForm.value.endCity
    )
  }

  // 路线类型筛选
  if (filterForm.value.type) {
    result = result.filter(route => 
      route.type === filterForm.value.type
    )
  }

  // 状态筛选
  if (showActiveOnly.value) {
    result = result.filter(route => route.status === 'active')
  }

  // 更新总数
  totalRoutes.value = result.length

  // 分页
  const startIndex = (currentPage.value - 1) * pageSize.value
  const endIndex = startIndex + pageSize.value
  return result.slice(startIndex, endIndex)
})

// 获取路线类型名称
const getRouteTypeName = (type) => {
  const typeMap = {
    'highway': '高速公路',
    'national': '国道',
    'provincial': '省道',
    'urban': '城市道路'
  }
  return typeMap[type] || '未知'
}

// 获取行样式
const getRowClassName = ({ row }) => {
  if (selectedRoute.value && row.id === selectedRoute.value.id) {
    return 'selected-row'
  }
  return ''
}

// 搜索路线
const searchRoutes = () => {
  currentPage.value = 1
  // 已通过计算属性实现
}

// 重置筛选
const resetFilter = () => {
  filterForm.value = {
    name: '',
    startCity: '',
    endCity: '',
    type: ''
  }
  searchRoutes()
}

// 筛选路线
const filterRoutes = () => {
  currentPage.value = 1
  // 已通过计算属性实现
}

// 刷新路线
const refreshRoutes = () => {
  loading.value = true
  
  // 实际应用中应该调用API获取最新数据
  setTimeout(() => {
    loading.value = false
    ElMessage.success('路线数据已刷新')
  }, 500)
}

// 选择路线
const selectRoute = (row) => {
  selectedRoute.value = row
  // 如果地图已加载，则在地图上高亮显示选中的路线
  if (mapLoaded.value && map.value) {
    highlightRoute(row)
  }
}

// 打开添加路线对话框
const openAddRouteDialog = () => {
  isEditMode.value = false
  routeForm.value = {
    id: null,
    name: '',
    startCity: '',
    endCity: '',
    type: 'highway',
    distance: 0,
    estimatedTime: '',
    viaPoints: [],
    status: 'active',
    remarks: ''
  }
  routeDialogVisible.value = true
}

// 编辑路线
const editRoute = (route) => {
  isEditMode.value = true
  routeForm.value = JSON.parse(JSON.stringify(route))
  routeDialogVisible.value = true
}

// 删除路线
const deleteRoute = (route) => {
  ElMessageBox.confirm(
    `确定要删除路线 "${route.name}" 吗？`,
    '确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 实际应用中应该调用API删除路线
    const index = routes.value.findIndex(item => item.id === route.id)
    if (index !== -1) {
      routes.value.splice(index, 1)
      
      // 如果删除的是当前选中的路线，清除选中
      if (selectedRoute.value && selectedRoute.value.id === route.id) {
        selectedRoute.value = null
      }
      
      ElMessage.success('路线已删除')
    }
  }).catch(() => {
    // 取消操作
  })
}

// 保存路线
const saveRoute = () => {
  routeFormRef.value.validate((valid) => {
    if (valid) {
      if (isEditMode.value) {
        // 编辑模式
        const index = routes.value.findIndex(item => item.id === routeForm.value.id)
        if (index !== -1) {
          routes.value[index] = JSON.parse(JSON.stringify(routeForm.value))
          
          // 如果编辑的是当前选中的路线，更新选中
          if (selectedRoute.value && selectedRoute.value.id === routeForm.value.id) {
            selectedRoute.value = routes.value[index]
          }
          
          ElMessage.success('路线已更新')
        }
      } else {
        // 添加模式
        const newRoute = JSON.parse(JSON.stringify(routeForm.value))
        newRoute.id = routes.value.length > 0 ? Math.max(...routes.value.map(item => item.id)) + 1 : 1
        routes.value.push(newRoute)
        ElMessage.success('路线已添加')
      }
      
      routeDialogVisible.value = false
    } else {
      return false
    }
  })
}

// 处理页面大小变化
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
}

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
}

// 地图相关
const mapContainer = ref(null)
const map = ref(null)
const mapLoaded = ref(false)
const routePolyline = ref(null)
const startMarker = ref(null)
const endMarker = ref(null)
const viaMarkers = ref([])
const mapZoom = ref(12)
const allRouteMarkers = ref([]) // 存储所有路线的标记
const allRoutePolylines = ref([]) // 存储所有路线的线条

// 高德地图API密钥
const amapKey = import.meta.env.VITE_AMAP_JS_KEY

// 初始化地图
const initMap = async () => {
  if (!mapContainer.value) return
  
  try {
    // 检查是否已经有AMap全局对象，避免重复加载
    if (window.AMap) {
      initMapInstance()
      return
    }
    
    // 加载高德地图
    const AMap = await loadAMapScript()
    
    initMapInstance()
  } catch (error) {
    console.error('地图加载失败:', error)
    ElMessage.error(`地图加载失败: ${error.message || '请检查API密钥是否正确'}`)
  }
}

// 加载高德地图脚本
const loadAMapScript = () => {
  return new Promise((resolve, reject) => {
    // 如果已经加载过，直接返回
    if (window.AMap) {
      resolve(window.AMap)
      return
    }
    
    // 设置安全配置 - 这一步必须在加载脚本前完成
    window._AMapSecurityConfig = {
      securityJsCode: import.meta.env.VITE_AMAP_SECURITY_CODE
    }
    
    // 创建script标签直接加载地图API
    const script = document.createElement('script')
    script.type = 'text/javascript'
    script.async = true
    // 使用JavaScript API Web服务密钥
    script.src = `https://webapi.amap.com/maps?v=2.0&key=${amapKey}&plugin=AMap.Scale,AMap.ToolBar,AMap.MapType,AMap.Driving`
    
    script.onerror = (e) => {
      console.error('高德地图脚本加载失败:', e)
      reject(new Error('高德地图脚本加载失败'))
    }
    
    script.onload = () => {
      // 延迟检查AMap对象，确保它已完全初始化
      setTimeout(() => {
        if (window.AMap) {
          console.log('高德地图脚本加载成功')
          resolve(window.AMap)
        } else {
          console.error('高德地图脚本加载成功但AMap对象不存在')
          reject(new Error('高德地图脚本加载成功但AMap对象不存在'))
        }
      }, 100)
    }
    
    document.head.appendChild(script)
  })
}

// 初始化地图实例
const initMapInstance = () => {
  // 创建地图实例
  map.value = new AMap.Map(mapContainer.value, {
    zoom: mapZoom.value,
    center: [116.397428, 39.90923], // 默认中心点（北京）
    resizeEnable: true
  })
  
  // 添加地图控件
  // 使用插件方式添加控件，而不是直接构造函数
  map.value.plugin(['AMap.Scale', 'AMap.ToolBar', 'AMap.MapType'], function() {
    // 添加比例尺控件
    map.value.addControl(new AMap.Scale());
    // 添加工具条控件
    map.value.addControl(new AMap.ToolBar());
    // 添加地图类型切换控件
    map.value.addControl(new AMap.MapType({
      defaultType: 0
    }));
  });
  
  mapLoaded.value = true
  
  // 显示所有路线
  showAllRoutes()
  
  // 如果有选中的路线，则在地图上高亮显示路线
  if (selectedRoute.value) {
    highlightRoute(selectedRoute.value)
  }
}

// 显示所有路线
const showAllRoutes = async () => {
  if (!map.value || !mapLoaded.value) return
  
  // 清除之前的所有标记和路线
  clearAllRoutes()
  
  // 创建所有路线的标记和路线
  for (const route of routes.value) {
    await createRouteOnMap(route, false) // 不高亮显示
  }
  
  // 调整地图视野以包含所有标记
  if (allRouteMarkers.value.length > 0) {
    map.value.setFitView(allRouteMarkers.value)
  }
}

// 在地图上创建路线
const createRouteOnMap = async (route, highlight = false) => {
  try {
    // 获取起点和终点的经纬度
    const startPosition = await geocodeAddress(route.startCity)
    const endPosition = await geocodeAddress(route.endCity)
    
    if (!startPosition || !endPosition) {
      console.warn(`无法获取路线 ${route.name} 的起点或终点位置`)
      return
    }
    
    // 创建起点标记
    const startMarkerInstance = new AMap.Marker({
      position: startPosition,
      map: map.value,
      icon: new AMap.Icon({
        size: new AMap.Size(25, 34),
        image: highlight 
          ? 'https://webapi.amap.com/theme/v1.3/markers/n/start.png'
          : 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
        imageSize: new AMap.Size(25, 34)
      }),
      title: `${route.name} - 起点: ${route.startCity}`
    })
    allRouteMarkers.value.push(startMarkerInstance)
    
    // 创建终点标记
    const endMarkerInstance = new AMap.Marker({
      position: endPosition,
      map: map.value,
      icon: new AMap.Icon({
        size: new AMap.Size(25, 34),
        image: highlight 
          ? 'https://webapi.amap.com/theme/v1.3/markers/n/end.png'
          : 'https://webapi.amap.com/theme/v1.3/markers/n/mark_r.png',
        imageSize: new AMap.Size(25, 34)
      }),
      title: `${route.name} - 终点: ${route.endCity}`
    })
    allRouteMarkers.value.push(endMarkerInstance)
    
    // 处理途经点
    const viaPositions = []
    if (route.viaPoints && route.viaPoints.length > 0) {
      for (const point of route.viaPoints) {
        const position = await geocodeAddress(point)
        if (position) {
          viaPositions.push(position)
          
          // 创建途经点标记
          const viaMarkerInstance = new AMap.Marker({
            position: position,
            map: map.value,
            icon: new AMap.Icon({
              size: new AMap.Size(25, 34),
              image: highlight 
                ? 'https://webapi.amap.com/theme/v1.3/markers/n/mid.png'
                : 'https://webapi.amap.com/theme/v1.3/markers/n/mark_bs.png',
              imageSize: new AMap.Size(25, 34)
            }),
            title: `${route.name} - 途经: ${point}`
          })
          allRouteMarkers.value.push(viaMarkerInstance)
        }
      }
    }
    
    // 创建路线
    const path = [startPosition, ...viaPositions, endPosition]
    const routePolylineInstance = new AMap.Polyline({
      path: path,
      strokeColor: highlight ? '#FF4500' : '#3370FF',
      strokeWeight: highlight ? 8 : 5,
      strokeOpacity: highlight ? 0.9 : 0.6,
      strokeStyle: highlight ? 'solid' : 'dashed',
      zIndex: highlight ? 120 : 100
    })
    routePolylineInstance.setMap(map.value)
    allRoutePolylines.value.push(routePolylineInstance)
    
    // 为路线添加点击事件
    routePolylineInstance.on('click', () => {
      const routeData = routes.value.find(r => r.name === route.name)
      if (routeData) {
        selectRoute(routeData)
      }
    })
    
    // 如果是高亮显示，则保存引用
    if (highlight) {
      routePolyline.value = routePolylineInstance
      startMarker.value = startMarkerInstance
      endMarker.value = endMarkerInstance
    }
    
    return { polyline: routePolylineInstance, markers: [startMarkerInstance, ...allRouteMarkers.value, endMarkerInstance] }
  } catch (error) {
    console.error(`创建路线 ${route.name} 失败:`, error)
    return null
  }
}

// 高亮显示选中的路线
const highlightRoute = async (route) => {
  if (!map.value || !mapLoaded.value) return
  
  // 先将所有路线设置为非高亮状态
  allRoutePolylines.value.forEach(polyline => {
    polyline.setOptions({
      strokeColor: '#3370FF',
      strokeWeight: 5,
      strokeOpacity: 0.6,
      strokeStyle: 'dashed',
      zIndex: 100
    })
  })
  
  // 清除之前的高亮标记
  clearMapOverlays()
  
  // 创建高亮路线
  await createRouteOnMap(route, true)
  
  // 调整地图视野以聚焦到选中的路线
  if (startMarker.value && endMarker.value) {
    map.value.setFitView([startMarker.value, endMarker.value, ...viaMarkers.value])
  }
}

// 清除地图上的标记和路线（仅清除高亮显示的部分）
const clearMapOverlays = () => {
  if (!map.value) return
  
  // 清除起点和终点标记
  if (startMarker.value) {
    startMarker.value.setMap(null)
    startMarker.value = null
  }
  
  if (endMarker.value) {
    endMarker.value.setMap(null)
    endMarker.value = null
  }
  
  // 清除途经点标记
  if (viaMarkers.value.length > 0) {
    viaMarkers.value.forEach(marker => marker.setMap(null))
    viaMarkers.value = []
  }
  
  // 清除路线
  if (routePolyline.value) {
    routePolyline.value.setMap(null)
    routePolyline.value = null
  }
}

// 清除所有路线和标记
const clearAllRoutes = () => {
  if (!map.value) return
  
  // 清除所有标记
  allRouteMarkers.value.forEach(marker => marker.setMap(null))
  allRouteMarkers.value = []
  
  // 清除所有路线
  allRoutePolylines.value.forEach(polyline => polyline.setMap(null))
  allRoutePolylines.value = []
  
  // 同时清除高亮显示的部分
  clearMapOverlays()
}

// 地址转换为经纬度
const geocodeAddress = async (address) => {
  return new Promise((resolve) => {
    // 这里应该使用高德地图的地理编码服务
    // 为了简化演示，这里使用模拟数据
    const mockGeoData = {
      '北京': [116.397428, 39.90923],
      '上海': [121.473701, 31.230416],
      '广州': [113.264385, 23.129112],
      '深圳': [114.057868, 22.543099],
      '杭州': [120.155070, 30.274085],
      '南京': [118.796877, 32.060255],
      '武汉': [114.305393, 30.593099],
      '成都': [104.065735, 30.659462],
      '重庆': [106.551556, 29.563009],
      '西安': [108.948024, 34.263161],
      '天津': [117.190182, 39.125596],
      '济南': [117.000923, 36.675807],
      '徐州': [117.184811, 34.261792],
      '合肥': [117.227239, 31.820586],
      '长沙': [112.982279, 28.19409],
      '郑州': [113.665412, 34.757975],
      '石家庄': [114.502461, 38.045474],
      '哈尔滨': [126.642464, 45.756967],
      '沈阳': [123.429096, 41.796767],
      '长春': [125.3245, 43.886841],
      '廊坊': [116.704441, 39.523927],
      '东莞': [113.746262, 23.046237],
      '苏州': [120.619585, 31.299379],
      '嘉兴': [120.750865, 30.762653]
    }
    
    // 如果有模拟数据，则返回对应的经纬度，否则返回null
    setTimeout(() => {
      resolve(mockGeoData[address] || null)
    }, 10) // 减少延迟时间，加快加载速度
  })
}

// 地图缩放控制
const zoomIn = () => {
  if (map.value) {
    mapZoom.value = Math.min(mapZoom.value + 1, 18)
    map.value.setZoom(mapZoom.value)
  }
}

const zoomOut = () => {
  if (map.value) {
    mapZoom.value = Math.max(mapZoom.value - 1, 3)
    map.value.setZoom(mapZoom.value)
  }
}

const resetMap = () => {
  if (map.value) {
    // 如果有选中的路线，则重新显示路线
    if (selectedRoute.value) {
      highlightRoute(selectedRoute.value)
    } else {
      // 否则重置到默认视图
      map.value.setZoom(12)
      map.value.setCenter([116.397428, 39.90923])
    }
  }
}

onMounted(() => {
  // 初始化
  refreshRoutes()
  initMap()
})

onUnmounted(() => {
  // 销毁地图实例
  if (map.value) {
    map.value.destroy()
    map.value = null
  }
})
</script>

<style scoped>
.route-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-title {
  display: flex;
  flex-direction: column;
}

.header-title h2 {
  margin: 0;
  font-size: 22px;
  color: #303133;
}

.subtitle {
  font-size: 14px;
  color: #909399;
  margin-top: 5px;
}

.filter-container {
  margin-bottom: 20px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
}

.content-row {
  margin-bottom: 20px;
}

.route-list-card {
  height: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.map-card {
  height: 100%;
}

.map-controls {
  display: flex;
  gap: 10px;
}

.map-container {
  position: relative;
  width: 100%;
  height: 400px;
  background-color: #f5f7fa;
}

.amap-container {
  width: 100%;
  height: 100%;
}

.map-loading {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: rgba(255, 255, 255, 0.7);
}

.loading-icon {
  font-size: 40px;
  color: var(--el-color-primary);
  animation: rotating 2s linear infinite;
}

@keyframes rotating {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.route-details {
  margin-top: 20px;
  padding: 15px;
  background-color: #f8f8f8;
  border-radius: 4px;
}

.route-details h3 {
  margin-top: 0;
  margin-bottom: 15px;
  color: #303133;
}

.selected-row {
  background-color: #ecf5ff;
}
</style>
